
#include "hj212_client_def.h"
#include "hj212_base_request.h"
#include "hj212_msg.h"
#include "hj212_pack.h"
#include "hj212_client_port.h"
/* *
 * 所有基本请求
 *
 * 简单的请求可以不必创建request结构体
 */

/* 1000 - 设置超时时间和重发次数 -  */
int hj212_request_1000_match(struct hj212_client *client, struct hj212_generalmsg *msg, uint32_t package_state)
{
    int res = hj212_standard_request_preprocessing(client, msg, package_state, 1000);
    if (res < 0)
    {
        return res;
    }
    if (!res)
    {
        const char *OverTime_p = strstr(msg->cp, "OverTime=");
        const char *ReCount_p = strstr(msg->cp, "ReCount=");
        if (!OverTime_p || !ReCount_p)
        {
            hj212_send_request_exe_result(client, REQUEST_EXE_RESULT_INVALID_PARAM, msg->parent.qn);
            return 0;
        }
        int OverTime = atoi(OverTime_p + strlen(OverTime_p));
        int ReCount = atoi(ReCount_p + strlen(ReCount_p));

        int res1 = hj212_client_command(client, SET_HJ212_STREAM_TIMEOUT, &OverTime);
        int res2 = hj212_client_command(client, SET_HJ212_MAXRET, &ReCount);

        if (!res1 && !res2)
            hj212_send_request_exe_result(client, REQUEST_EXE_RESULT_SUCCEED, msg->parent.qn);
        else
            hj212_send_request_exe_result(client, REQUEST_EXE_RESULT_UNKNOWN_ERROR, msg->parent.qn);
    }
    return 0;
}

/* 1011 提取现场机时间 - 暂时不支持操作下级设备 */
int hj212_request_1011_match(struct hj212_client *client, struct hj212_generalmsg *msg, uint32_t package_state)
{
    if (msg->parent.cn != 1011)
    {
        return -1;
    }
    /* 捕捉到上位机的请求 */
    enum request_response response = hj212_check_request_msg(client, msg, package_state);
    if (response != REQUEST_RESPONSE_ACCEPT)
    {
        hj212_send_request_response(client, response, msg->parent.qn);
        return 0;
    }
    /* 暂时不支持操作下级设备 */
    if (!(package_state & UNPACK_NO_CP))
    {
        hj212_send_request_response(client, REQUEST_RESPONSE_REPULSE, msg->parent.qn);
        return 0;
    }
    hj212_send_request_response(client, REQUEST_RESPONSE_ACCEPT, msg->parent.qn);

    struct tm time;
    time_t current = hj212_client_current_timestamp(client);
    if (localtime_r(&current, &time))
    {
        hj212_send_local_pack(client, msg->parent.qn, NULL, 1011, 0, NULL,
                              "SystemTime=%04d%02d%02d%02d%02d%02d;",
                              (time).tm_year + 1900, (time).tm_mon + 1, (time).tm_mday,
                              (time).tm_hour, (time).tm_min, (time).tm_sec);
        hj212_send_request_exe_result(client, REQUEST_EXE_RESULT_SUCCEED, msg->parent.qn);
    }
    else
    {
        hj212_send_request_exe_result(client, REQUEST_EXE_RESULT_FAULT, msg->parent.qn);
    }
    return 0;
}

/* 1012 设置现场机时间 - 暂时不支持操作下级设备 */

/* 1013 现场机时间校准 - 暂时不支持操作下级设备 */

/* 2011 启动实时数据 */